package com.yl.solution.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.yl.solution.dao.BaseDAO;

@SuppressWarnings("all")
@Repository
public class BaseDAOImpl<T> implements BaseDAO<T> {

	private SessionFactory sessionFactory;
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	private Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
	
	@Override
	public Serializable save(T obj) {
		return this.getCurrentSession().save(obj);
	}

	@Override
	public void delete(T obj) {
		this.getCurrentSession().delete(obj);
	}

	@Override
	public void update(T obj) {
		this.getCurrentSession().update(obj);
	}

	public T get(Class<T> c, Serializable id) {
		return (T) this.getCurrentSession().get(c, id);
	}
	
	@Override
	public List<T> find(String sql) {
		return this.getCurrentSession().createSQLQuery(sql).list();
	}

	@Override
	public List<T> find(String sql, Object[] param) {
		Query query = this.getCurrentSession().createSQLQuery(sql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
		}
		return query.list();
	}

	@Override
	public List<T> find(String sql, List<Object> param) {
		Query query = this.getCurrentSession().createSQLQuery(sql);
		if (param != null && param.size() >0) {
			for (int i = 0; i < param.size(); i++) {
				query.setParameter(i, param.get(i));
			}
		}
		return query.list();
	}

	@Override
	public List<T> find(String sql, Object[] param, Integer page, Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query query = this.getCurrentSession().createSQLQuery(sql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				query.setParameter(i, param[i]);
			}
		}
		return query.setFirstResult((page-1)*rows).setMaxResults(rows).list();
	}

}
